package com.myblog.controller;

import com.myblog.constant.CodeType;
import com.myblog.redis.RedisService;
import com.myblog.service.TagService;
import com.myblog.utils.DataMap;
import com.myblog.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@Slf4j
@RestController
public class IndexController {

    @Autowired
    private TagService tagService;

    @Autowired
    private RedisService redisService;

    /**
     * 获取标签云
     * @return
     */
    @GetMapping("/findTagsCloud")
    public String getTagsCloud(){
        try{
            //获取标签列表信息
            DataMap data = tagService.getTagsCloud();

            return JsonResult.build(data).toJSON();
        }catch (Exception e){
            log.error("ArticleAndTagsController getTagsCloud Exception",e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }

    @PostMapping("/getUserNews")
    public String getUserNews(@AuthenticationPrincipal Principal principal, HttpServletRequest request){
        try{
            Principal userPrincipal = request.getUserPrincipal();
            if(userPrincipal == null){
                return JsonResult.fail(CodeType.USER_NOT_LOGIN).toJSON();
            }
            String userPhone = userPrincipal.getName();

            DataMap data = redisService.getUserNews(userPhone);

            return JsonResult.build(data).toJSON();
        }catch (Exception e){
            log.error("ArticleAndTagsController getTagsCloud Exception",e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }
}
